package com.xuanjia.smart_interview.job.once;

import cn.hutool.core.collection.CollUtil;
import com.xuanjia.smart_interview.esdao.QuestionEsDao;
import com.xuanjia.smart_interview.model.dto.question.QuestionEsDTO;
import com.xuanjia.smart_interview.model.entity.Question;
import com.xuanjia.smart_interview.service.QuestionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Component
@Slf4j
public class FullSyncQuestionToEs implements CommandLineRunner {

    @Resource
    private QuestionService questionService;

    @Resource
    private QuestionEsDao questionEsDao;

    /**
     * 向 Es 全量写入数据
     * @param args
     * @throws Exception
     */
    @Override
    public void run(String... args) throws Exception {
        List<Question> questionList = questionService.list();
        if (CollUtil.isEmpty(questionList)){
            return ;
        }
        List<QuestionEsDTO> questionEsDTOS = questionList.stream()
                .map(QuestionEsDTO::objToDto)
                .collect(Collectors.toList());
        int total = questionList.size();
        int pageSize = 500;
        for (int i = 0; i < total; i += pageSize) {
            int pageEnd = Math.min(i + pageSize, total);
            questionEsDao.saveAll(questionEsDTOS.subList(i,pageEnd));
        }
    }


}
